/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.report.statistics.siteManagement;

import com.koron.common.bean.DepartmentTreeBean;
import com.koron.common.domain.KpiStatistics;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.common.generator.GetHardwareIdFailedException;
import com.koron.common.generator.InvalidSystemClockException;
import com.koron.common.service.KpiStatisticsService;
import com.koron.common.web.Util;
import com.koron.purpose.mapper.KPITemplateMapper;
import com.koron.report.bean.StatisticsBean;
import com.koron.report.management.StatisticsManagement;
import com.koron.report.mapper.statistics.CheckPassRateSafetyToolsMapper;
import com.koron.report.statistics.Contants;
import com.koron.report.statistics.StatisticsService;
import com.koron.risk.bean.CorpBean;
import com.koron.risk.service.api.CorpManagementService;
import com.koron.risk.util.BusinessCode;
import com.koron.system.domain.District;
import com.koron.system.domain.DistrictCorpRelation;
import com.koron.system.mapper.DistrictMapper;
import com.koron.system.service.api.DistrictService;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.swan.bean.MessageBean;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 安全工器具检查合格率
 */
@Service("checkPassRateSafetyToolsService")
@SuppressWarnings("deprecation")
public class CheckPassRateSafetyToolsServiceImpl implements InitializingBean, StatisticsService {
    // 设备类型id,引用数据字典：安全工器具检设备类型id
    private final String DEVICE_TYPE_ID = "1187936408603381760";

    // 指标code:安全工器具检查合格总数
    private final String KPICODE_QUALIFIEDTOTAL = "0062";
    // 指标code:安全工器具检查总数
    private final String KPICODE_TOTAL = "0063";
    // 指标code:安全工器具检查合格率
    private final String KPICODE_PERCENTPASS = "0064";

    private final Logger logger = LoggerFactory.getLogger(CheckPassRateSafetyToolsServiceImpl.class);

    @Autowired
    private StatisticsManagement statisticsManagement;

    @Autowired
    private KpiStatisticsService kpiStatisticsService;

    @Autowired
    private CorpManagementService corpManagementService;

    // 获取片区信息service
    @Autowired
    private DistrictService districtService;

    @Autowired
    private Util util;

    @Override
    public void afterPropertiesSet() throws Exception {
        Set<Object> handlers = statisticsManagement.getHandlers();
        handlers.add(this);
    }

    @Override
    public void statisticsMonth(int year, int month) {
        SessionFactory factory = null;
        try {
            factory = new SessionFactory();
            CheckPassRateSafetyToolsMapper mapper = factory.getMapper(CheckPassRateSafetyToolsMapper.class);
            Calendar calendar = Calendar.getInstance();
            calendar.set(year, month - 1, 1, 0, 0, 0);
            Date startDate = calendar.getTime();
            calendar.add(Calendar.MONTH, 1);
            Date stopDate = calendar.getTime();
            // 安全工器具检查合格总数 指标名称
            String kpiNameQualifiedTotal = factory.getMapper(KPITemplateMapper.class).queryTemplateByCode(KPICODE_QUALIFIEDTOTAL).getName();
            // 安全工器具检查总数 指标名称
            String kpiNameTotal = factory.getMapper(KPITemplateMapper.class).queryTemplateByCode(KPICODE_TOTAL).getName();
            // 安全工器具检查合格率 指标名称
            String kpiNamePercentPass = factory.getMapper(KPITemplateMapper.class).queryTemplateByCode(KPICODE_PERCENTPASS).getName();
            String dateValue = year + "-" + month;
            if (month < 10) {
                dateValue = year + "-0" + month;
            }
            // 按检查人员
            personTotal(mapper, kpiNameQualifiedTotal, kpiNameTotal, kpiNamePercentPass,
                    Contants.DATE_TYPE_1, dateValue, Contants.STATISTICAL_TYPE_1, startDate, stopDate);
            // 按部门
            deptTotal(mapper, kpiNameQualifiedTotal, kpiNameTotal, kpiNamePercentPass,
                    Contants.DATE_TYPE_1, dateValue, Contants.STATISTICAL_TYPE_2, startDate, stopDate);
            // 按公司
            companyTotal(mapper, kpiNameQualifiedTotal, kpiNameTotal, kpiNamePercentPass,
                    Contants.DATE_TYPE_1, dateValue, Contants.STATISTICAL_TYPE_3, startDate, stopDate);
            // 按片区
            areaTotal(factory, mapper, kpiNameQualifiedTotal, kpiNameTotal, kpiNamePercentPass,
                    Contants.DATE_TYPE_1, dateValue, Contants.STATISTICAL_TYPE_4, startDate, stopDate);
            // 按集团
            blocTotal(mapper, kpiNameQualifiedTotal, kpiNameTotal, kpiNamePercentPass,
                    Contants.DATE_TYPE_1, dateValue, Contants.STATISTICAL_TYPE_5, startDate, stopDate);
        } catch (Exception e) {
            if (factory != null) {
                factory.close(false);
            }
            logger.error(e.getMessage(),e);
            logger.error(String.format("安全工器具检查合格率按月(%o-%o)统计执行发生错误", year, month));
        }finally {
            if (factory != null) {
                factory.close();
            }
        }
    }

    @Override
    public void statisticsQuarter(int year, int quarter) {
        SessionFactory factory = null;
        try {
            factory = new SessionFactory();
            CheckPassRateSafetyToolsMapper mapper = factory.getMapper(CheckPassRateSafetyToolsMapper.class);
            Calendar calendar = Calendar.getInstance();
            int month = (quarter - 1) * 3 + 1;
            calendar.set(year, month - 1, 1, 0, 0, 0);
            Date startDate = calendar.getTime();
            calendar.add(Calendar.MONTH, 3);
            Date stopDate = calendar.getTime();
            // 安全工器具检查合格总数 指标名称
            String kpiNameQualifiedTotal = factory.getMapper(KPITemplateMapper.class).queryTemplateByCode(KPICODE_QUALIFIEDTOTAL).getName();
            // 安全工器具检查总数 指标名称
            String kpiNameTotal = factory.getMapper(KPITemplateMapper.class).queryTemplateByCode(KPICODE_TOTAL).getName();
            // 安全工器具检查合格率 指标名称
            String kpiNamePercentPass = factory.getMapper(KPITemplateMapper.class).queryTemplateByCode(KPICODE_PERCENTPASS).getName();

            String dateValue = year + "-" + quarter;
            // 按检查人员
            personTotal(mapper, kpiNameQualifiedTotal, kpiNameTotal, kpiNamePercentPass,
                    Contants.DATE_TYPE_2, dateValue, Contants.STATISTICAL_TYPE_1, startDate, stopDate);
            // 按部门
            deptTotal(mapper, kpiNameQualifiedTotal, kpiNameTotal, kpiNamePercentPass,
                    Contants.DATE_TYPE_2, dateValue, Contants.STATISTICAL_TYPE_2, startDate, stopDate);
            // 按公司
            companyTotal(mapper, kpiNameQualifiedTotal, kpiNameTotal, kpiNamePercentPass,
                    Contants.DATE_TYPE_2, dateValue, Contants.STATISTICAL_TYPE_3, startDate, stopDate);
            // 按片区
            areaTotal(factory, mapper, kpiNameQualifiedTotal, kpiNameTotal, kpiNamePercentPass,
                    Contants.DATE_TYPE_2, dateValue, Contants.STATISTICAL_TYPE_4, startDate, stopDate);
            // 按集团
            blocTotal(mapper, kpiNameQualifiedTotal, kpiNameTotal, kpiNamePercentPass,
                    Contants.DATE_TYPE_2, dateValue, Contants.STATISTICAL_TYPE_5, startDate, stopDate);
        } catch (Exception e) {
            if (factory != null) {
                factory.close(false);
            }
            logger.error(e.getMessage(),e);
            logger.error(String.format("安全工器具检查合格率按季度(%o-%o季度)统计执行发生错误", year, quarter));
        }finally {
            if (factory != null) {
                factory.close();
            }
        }
    }

    @Override
    public void statisticsYear(int year) {
        SessionFactory factory = null;
        try {
            factory = new SessionFactory();
            CheckPassRateSafetyToolsMapper mapper = factory.getMapper(CheckPassRateSafetyToolsMapper.class);
            Calendar calendar = Calendar.getInstance();
            calendar.set(year, 0, 1, 0, 0, 0);
            Date startDate = calendar.getTime();
            calendar.add(Calendar.YEAR, 1);
            Date stopDate = calendar.getTime();
            // 安全工器具检查合格总数 指标名称
            String kpiNameQualifiedTotal = factory.getMapper(KPITemplateMapper.class).queryTemplateByCode(KPICODE_QUALIFIEDTOTAL).getName();
            // 安全工器具检查总数 指标名称
            String kpiNameTotal = factory.getMapper(KPITemplateMapper.class).queryTemplateByCode(KPICODE_TOTAL).getName();
            // 安全工器具检查合格率 指标名称
            String kpiNamePercentPass = factory.getMapper(KPITemplateMapper.class).queryTemplateByCode(KPICODE_PERCENTPASS).getName();

            String dateValue = String.valueOf(year);
            // 按检查人员
            personTotal(mapper, kpiNameQualifiedTotal, kpiNameTotal, kpiNamePercentPass,
                    Contants.DATE_TYPE_3, dateValue, Contants.STATISTICAL_TYPE_1, startDate, stopDate);
            // 按部门
            deptTotal(mapper, kpiNameQualifiedTotal, kpiNameTotal, kpiNamePercentPass,
                    Contants.DATE_TYPE_3, dateValue, Contants.STATISTICAL_TYPE_2, startDate, stopDate);
            // 按公司
            companyTotal(mapper, kpiNameQualifiedTotal, kpiNameTotal, kpiNamePercentPass,
                    Contants.DATE_TYPE_3, dateValue, Contants.STATISTICAL_TYPE_3, startDate, stopDate);
            // 按片区
            areaTotal(factory, mapper, kpiNameQualifiedTotal, kpiNameTotal, kpiNamePercentPass,
                    Contants.DATE_TYPE_3, dateValue, Contants.STATISTICAL_TYPE_4, startDate, stopDate);
            // 按集团
            blocTotal(mapper, kpiNameQualifiedTotal, kpiNameTotal, kpiNamePercentPass,
                    Contants.DATE_TYPE_3, dateValue, Contants.STATISTICAL_TYPE_5, startDate, stopDate);
        } catch (Exception e) {
            if (factory != null) {
                factory.close(false);
            }
            logger.error("安全工器具检查合格率按年(" + year + ")统计执行发生错误");
        }finally {
            if (factory != null) {
                factory.close();
            }
        }
    }

    /**
     * 按检查人员 统计
     *
     * @param mapper
     * @param kpiNameQualifiedTotal 安全工器具检查合格总数 指标名称
     * @param kpiNameTotal          安全工器具检查总数 指标名称
     * @param kpiNamePercentPass    安全工器具检查合格率 指标名称
     * @param dateType              日期类型 1月，2季，3年
     * @param dateValue             日期 月：2020-01，季2020-1/2/3/4,年2020
     * @param statisticalType       统计类型：1员工，2部门，3公司，4片区，5集团
     * @param startDate
     * @param stopDate
     */
    private void personTotal(CheckPassRateSafetyToolsMapper mapper, String kpiNameQualifiedTotal, String kpiNameTotal,
                             String kpiNamePercentPass, Integer dateType, String dateValue, Integer statisticalType,
                             Date startDate, Date stopDate) throws GetHardwareIdFailedException, InvalidSystemClockException {
        // 统计查询:安全工器具检查合格总数
        List<StatisticsBean> qualifiedTotalList = mapper.statisticsQualifiedTotalPerson(startDate, stopDate, DEVICE_TYPE_ID);
        // 统计查询:安全工器具检查总数
        List<StatisticsBean> totalList = mapper.statisticsTotalPerson(startDate, stopDate, DEVICE_TYPE_ID);
        // 组装数据：进行统计指标添加
        assemblyData(totalList, qualifiedTotalList, kpiNameQualifiedTotal, kpiNameTotal,
                kpiNamePercentPass, dateType, dateValue, statisticalType);
    }

    /**
     * 按部门 统计
     *
     * @param mapper
     * @param kpiNameQualifiedTotal 安全工器具检查合格总数 指标名称
     * @param kpiNameTotal          安全工器具检查总数 指标名称
     * @param kpiNamePercentPass    安全工器具检查合格率 指标名称
     * @param dateType              日期类型 1月，2季，3年
     * @param dateValue             日期 月：2020-01，季2020-1/2/3/4,年2020
     * @param statisticalType       统计类型：1员工，2部门，3公司，4片区，5集团
     * @param startDate
     * @param stopDate
     */
    private void deptTotal(CheckPassRateSafetyToolsMapper mapper, String kpiNameQualifiedTotal, String kpiNameTotal,
                           String kpiNamePercentPass, Integer dateType, String dateValue, Integer statisticalType,
                           Date startDate, Date stopDate) throws GetHardwareIdFailedException, InvalidSystemClockException {
        // 统计查询:安全工器具检查合格总数
        List<StatisticsBean> qualifiedTotalList = mapper.statisticsQualifiedTotalDept(startDate, stopDate, DEVICE_TYPE_ID);
        // 统计查询:安全工器具检查总数
        List<StatisticsBean> totalList = mapper.statisticsTotalDept(startDate, stopDate, DEVICE_TYPE_ID);
        if (totalList == null || totalList.size() <= 0) {
            return;
        }
        //先获取当前组织架构上所有的部门
        List<DepartmentTreeBean> departmentTreeBeanList = (List<DepartmentTreeBean>) util.depttree(Contants.BLOC_CODE, 1).getData();
        if (departmentTreeBeanList == null || departmentTreeBeanList.size() <= 0) {
            return;
        }
        // 将当前获取的所有部门排除当前为水司，以及当前集团的的code
        //先排除集团
        departmentTreeBeanList = departmentTreeBeanList.stream()
                .filter(dept -> !Contants.BLOC_CODE.equals(dept.getDepartmentCode()))
                .collect(Collectors.toList());
        //获取当前标志为水司的部门（组织架构）
        List<CorpBean> corpBeanList = corpManagementService.corpBeanList();
        List<String> corpCodeList = corpBeanList.stream()
                .map(corpBean -> corpBean.getCorpCode())
                .collect(Collectors.toList());
        //再排除水司
        departmentTreeBeanList = departmentTreeBeanList.stream()
                .filter(dept -> !(corpCodeList.contains(dept.getDepartmentCode())))
                .collect(Collectors.toList());
        if (departmentTreeBeanList == null || departmentTreeBeanList.size() <= 0) {
            return;
        }
        // 安全工器具检查合格总数
        List<StatisticsBean> qualifiedTotals = new LinkedList<>();
        // 安全工器具检查总数
        List<StatisticsBean> totals = new LinkedList<>();
        MessageBean<?> msg;
        List<String> codes;
        List<DepartmentTreeBean> list;
        float value;
        for (DepartmentTreeBean departmentTreeBean : departmentTreeBeanList) {
            //查询该部门下所有子部门
            msg = util.depttree(departmentTreeBean.getDepartmentCode(), 1);
            codes = new LinkedList<>();
            if (msg.getData() != null) {
                list = (List<DepartmentTreeBean>) msg.getData();
                codes = list.stream().map(bean -> bean.getDepartmentCode()).collect(Collectors.toList());
            } else {
                codes.add(departmentTreeBean.getDepartmentCode());
            }
            value = 0f;
            for (StatisticsBean bean : totalList) {
                if (codes.contains(bean.getCode())) {
                    value += Float.valueOf(bean.getValue());
                }
            }
            if (value != 0f) {
                totals.add(new StatisticsBean(departmentTreeBean.getDepartmentCode(), departmentTreeBean.getName(), String.valueOf(value)));
            }
            if (qualifiedTotalList != null && qualifiedTotalList.size() > 0) {
                value = 0f;
                for (StatisticsBean bean : qualifiedTotalList) {
                    if (codes.contains(bean.getCode())) {
                        value += Float.valueOf(bean.getValue());
                    }
                }
                if (value != 0f) {
                    qualifiedTotals.add(new StatisticsBean(departmentTreeBean.getDepartmentCode(), departmentTreeBean.getName(), String.valueOf(value)));
                }
            }
        }
        // 组装数据：进行统计指标添加
        assemblyData(totals, qualifiedTotals, kpiNameQualifiedTotal, kpiNameTotal,
                kpiNamePercentPass, dateType, dateValue, statisticalType);
    }

    /**
     * 按公司 统计
     *
     * @param mapper
     * @param kpiNameQualifiedTotal 安全工器具检查合格总数 指标名称
     * @param kpiNameTotal          安全工器具检查总数 指标名称
     * @param kpiNamePercentPass    安全工器具检查合格率 指标名称
     * @param dateType              日期类型 1月，2季，3年
     * @param dateValue             日期 月：2020-01，季2020-1/2/3/4,年2020
     * @param statisticalType       统计类型：1员工，2部门，3公司，4片区，5集团
     * @param startDate
     * @param stopDate
     */
    private void companyTotal(CheckPassRateSafetyToolsMapper mapper, String kpiNameQualifiedTotal, String kpiNameTotal,
                              String kpiNamePercentPass, Integer dateType, String dateValue, Integer statisticalType,
                              Date startDate, Date stopDate) throws GetHardwareIdFailedException, InvalidSystemClockException {
        // 统计查询:安全工器具检查合格总数
        List<StatisticsBean> qualifiedTotalList = mapper.statisticsQualifiedTotal(startDate, stopDate, DEVICE_TYPE_ID);
        // 统计查询:安全工器具检查总数
        List<StatisticsBean> totalList = mapper.statisticsTotal(startDate, stopDate, DEVICE_TYPE_ID);
        if (totalList != null && totalList.size() > 0) {
            MessageBean<CorpBean> corpBean;
            for (StatisticsBean statisticsBean : totalList) {
                // 获取水司名称
                corpBean = corpManagementService.getOne(statisticsBean.getCode());
                if (corpBean.getCode() == BusinessCode.MESSAGE_CODE_SUCCESS) {
                    statisticsBean.setCodeName(corpBean.getData().getCorpName());
                } else {
                    statisticsBean.setCodeName("");
                }
            }
        }
        // 组装数据：进行统计指标添加
        assemblyData(totalList, qualifiedTotalList, kpiNameQualifiedTotal, kpiNameTotal,
                kpiNamePercentPass, dateType, dateValue, statisticalType);
    }

    /**
     * 按片区 统计
     *
     * @param factory
     * @param mapper
     * @param kpiNameQualifiedTotal 安全工器具检查合格总数 指标名称
     * @param kpiNameTotal          安全工器具检查总数 指标名称
     * @param kpiNamePercentPass    安全工器具检查合格率 指标名称
     * @param dateType              日期类型 1月，2季，3年
     * @param dateValue             日期 月：2020-01，季2020-1/2/3/4,年2020
     * @param statisticalType       统计类型：1员工，2部门，3公司，4片区，5集团
     * @param startDate
     * @param stopDate
     * @throws GetHardwareIdFailedException
     * @throws InvalidSystemClockException
     */
    private void areaTotal(SessionFactory factory, CheckPassRateSafetyToolsMapper mapper, String kpiNameQualifiedTotal, String kpiNameTotal,
                           String kpiNamePercentPass, Integer dateType, String dateValue, Integer statisticalType,
                           Date startDate, Date stopDate) throws GetHardwareIdFailedException, InvalidSystemClockException {
        // 统计查询:安全工器具检查合格总数
        List<StatisticsBean> qualifiedTotalList = mapper.statisticsQualifiedTotal(startDate, stopDate, DEVICE_TYPE_ID);
        // 统计查询:安全工器具检查总数
        List<StatisticsBean> totalList = mapper.statisticsTotal(startDate, stopDate, DEVICE_TYPE_ID);
        List<District> districtList = factory.getMapper(DistrictMapper.class).queryAllDistrict(null, null);
        if (districtList != null && districtList.size() > 0) {
            // 检查合格总数
            List<StatisticsBean> statisticsTotalBeans = new LinkedList<>();
            // 检查总数
            List<StatisticsBean> statisticsQualifiedTotalBeans = new LinkedList<>();
            for (District district : districtList) {
                // 根据片区code，获取片区下所有公司信息
                List<DistrictCorpRelation> districtCorpRelationList = districtService.queryAssociatedCorp(district.getCode());
                float valueTotal = 0f;
                float valueQualifiedTotal = 0f;
                if (districtCorpRelationList != null && districtCorpRelationList.size() > 0) {
                    for (DistrictCorpRelation districtCorpRelation : districtCorpRelationList) {
                        // 根据code 获取value值
                        valueTotal += getValueByCode(totalList, districtCorpRelation.getCorpCode());
                        // 根据code 获取value值
                        valueQualifiedTotal += getValueByCode(qualifiedTotalList, districtCorpRelation.getCorpCode());
                    }
                }
                statisticsTotalBeans.add(new StatisticsBean(district.getCode(), district.getName(), Float.valueOf(valueTotal).toString()));
                statisticsQualifiedTotalBeans.add(new StatisticsBean(district.getCode(), district.getName(), Float.valueOf(valueQualifiedTotal).toString()));
            }
            // 组装数据：进行统计指标添加
            assemblyData(statisticsTotalBeans, statisticsQualifiedTotalBeans, kpiNameQualifiedTotal, kpiNameTotal,
                    kpiNamePercentPass, dateType, dateValue, statisticalType);
        }
    }

    /**
     * 按集团 统计
     *
     * @param mapper
     * @param kpiNameQualifiedTotal 安全工器具检查合格总数 指标名称
     * @param kpiNameTotal          安全工器具检查总数 指标名称
     * @param kpiNamePercentPass    安全工器具检查合格率 指标名称
     * @param dateType              日期类型 1月，2季，3年
     * @param dateValue             日期 月：2020-01，季2020-1/2/3/4,年2020
     * @param statisticalType       统计类型：1员工，2部门，3公司，4片区，5集团
     * @param startDate
     * @param stopDate
     * @throws GetHardwareIdFailedException
     * @throws InvalidSystemClockException
     */
    private void blocTotal(CheckPassRateSafetyToolsMapper mapper, String kpiNameQualifiedTotal, String kpiNameTotal,
                           String kpiNamePercentPass, Integer dateType, String dateValue, Integer statisticalType,
                           Date startDate, Date stopDate) throws GetHardwareIdFailedException, InvalidSystemClockException {
        // 统计查询:安全工器具检查总数
        Integer totalValue = mapper.statisticsTotalBloc(startDate, stopDate, DEVICE_TYPE_ID);
        List<StatisticsBean> totalList = new ArrayList<>();
        totalList.add(new StatisticsBean(Contants.BLOC_CODE, Contants.BLOC_NAME, String.valueOf(totalValue)));
        // 统计查询:安全工器具检查合格总数
        Integer qualifiedTotalValue = mapper.statisticsQualifiedTotalBloc(startDate, stopDate, DEVICE_TYPE_ID);
        List<StatisticsBean> qualifiedTotalList = new ArrayList<>();
        qualifiedTotalList.add(new StatisticsBean(Contants.BLOC_CODE, Contants.BLOC_NAME, String.valueOf(qualifiedTotalValue)));
        // 组装数据：进行统计指标添加
        assemblyData(totalList, qualifiedTotalList, kpiNameQualifiedTotal, kpiNameTotal,
                kpiNamePercentPass, dateType, dateValue, statisticalType);
    }

    /**
     * 组装数据：进行统计指标添加
     *
     * @param totalList             统计查询 安全工器具检查合格总数
     * @param qualifiedTotalList    统计查询 安全工器具检查合格总数list
     * @param kpiNameQualifiedTotal 安全工器具检查合格总数 指标名称
     * @param kpiNameTotal          安全工器具检查总数 指标名称
     * @param kpiNamePercentPass    安全工器具检查合格率 指标名称
     * @param dateType              日期类型 1月，2季，3年
     * @param dateValue             日期 月：2020-01，季2020-1/2/3/4,年2020
     * @param statisticalType       统计类型：1员工，2部门，3公司，4片区，5集团
     * @throws GetHardwareIdFailedException
     * @throws InvalidSystemClockException
     */
    private void assemblyData(List<StatisticsBean> totalList, List<StatisticsBean> qualifiedTotalList,
                              String kpiNameQualifiedTotal, String kpiNameTotal, String kpiNamePercentPass,
                              Integer dateType, String dateValue, Integer statisticalType) throws GetHardwareIdFailedException, InvalidSystemClockException {
        // 统计查询:安全工器具检查合格率
        if (totalList != null && totalList.size() > 0) {
            List<KpiStatistics> insertList = new LinkedList<>();
            for (StatisticsBean statisticsBean : totalList) {
                float value = 0f;
                // 安全工器具检查合格总数
                if (qualifiedTotalList != null && qualifiedTotalList.size() > 0) {
                    for (StatisticsBean qualifiedTotal : qualifiedTotalList) {
                        if (statisticsBean.getCode().equals(qualifiedTotal.getCode())) {
                            value = Float.valueOf(qualifiedTotal.getValue());
                            break;
                        }
                    }
                }
                insertList.add(new KpiStatistics(
                        DefaultIdGenerator.getInstance().generateLongId(),
                        kpiNameQualifiedTotal,
                        KPICODE_QUALIFIEDTOTAL,
                        value,
                        dateType,
                        dateValue,
                        statisticalType,
                        statisticsBean.getCode(),
                        statisticsBean.getCodeName(),
                        new Date()
                ));
                // 安全工器具检查总数
                insertList.add(new KpiStatistics(
                        DefaultIdGenerator.getInstance().generateLongId(),
                        kpiNameTotal,
                        KPICODE_TOTAL,
                        Float.valueOf(statisticsBean.getValue()),
                        dateType,
                        dateValue,
                        statisticalType,
                        statisticsBean.getCode(),
                        statisticsBean.getCodeName(),
                        new Date()
                ));
                // 安全工器具检查合格率
                float percentPass = Float.valueOf(statisticsBean.getValue());
                if (percentPass != 0f) {
                    percentPass = value / percentPass;
                }
                insertList.add(new KpiStatistics(
                        DefaultIdGenerator.getInstance().generateLongId(),
                        kpiNamePercentPass,
                        KPICODE_PERCENTPASS,
                        percentPass,
                        dateType,
                        dateValue,
                        statisticalType,
                        statisticsBean.getCode(),
                        statisticsBean.getCodeName(),
                        new Date()
                ));
                kpiStatisticsService.delete(KPICODE_QUALIFIEDTOTAL, dateValue, statisticsBean.getCode());
                kpiStatisticsService.delete(KPICODE_TOTAL, dateValue, statisticsBean.getCode());
                kpiStatisticsService.delete(KPICODE_PERCENTPASS, dateValue, statisticsBean.getCode());
            }
            kpiStatisticsService.batchInsert(insertList);
        }
    }

    /**
     * 根据code 获取value值
     *
     * @param list
     * @param code
     */
    private float getValueByCode(List<StatisticsBean> list, String code) {
        if (list != null && list.size() > 0) {
            for (StatisticsBean statisticsBean : list) {
                if (statisticsBean.getCode().equals(code)) {
                    return Float.valueOf(statisticsBean.getValue());
                }
            }
        }
        return 0f;
    }
}
